import { useLocation, useNavigate } from "react-router-dom";
import { getToken } from "@/utils/auth";
import { useEffect } from "react";
// 没有 Token 也可访问的白名单页面
const WHITE_LIST = ["/login", "/404"];

export function usePermisssionGuard(routes) {
  let location = useLocation();
  let navigate = useNavigate();
  const token = getToken();
  useEffect(() => {
    if (!token) {
      //判断是否为白名单
      if (WHITE_LIST.includes(location.pathname)) {
        return; //放行
      }
      //重定向登录页
      navigate({
        pathname: "/login",
      });
      return;
    }
    if (location.pathname === "/login") {
      //存在token进入首页
      navigate("/");
      return;
    }
    //放行
  });
}
